<template>
  <v-chart style="height: 245px" class="chart" :option="option" autoresize />
</template>

<script setup>
import { color, use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { BarChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import VChart from "vue-echarts";
import { ref, watch, defineProps } from "vue";

use([
  CanvasRenderer,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
]);

const props = defineProps({
  xAxisData: {
    type: Array,
    default: () => [],
  },
  seriesData: {
    type: Array,
    default: () => [],
  },
});
// 生成一组适合深色背景的渐变色
const generateGradientColors = (count) => {
  const baseColors = [
    ["#4facfe", "#00f2fe"], // 蓝-青渐变
    ["#ff758c", "#ff7eb3"], // 粉-玫红渐变
    ["#6a11cb", "#2575fc"], // 紫-蓝渐变
    ["#f83600", "#f9d423"], // 橙-黄渐变
    ["#43e97b", "#38f9d7"], // 绿-青渐变
    ["#ff0844", "#ffb199"], // 红-橙渐变
  ];

  return baseColors.slice(0, count).map((color) => ({
    type: "linear",
    x: 0,
    y: 0,
    x2: 0,
    y2: 1,
    colorStops: [
      { offset: 0, color: color[0] },
      { offset: 1, color: color[1] },
    ],
  }));
};
const option = ref({
  title: {
    show: false,
  },
  color: "#fff5a7",
  tooltip: {
    trigger: "axis",
    formatter: (params) => {
      const data = params[0];
      return `${data.marker}${data.axisValueLabel}: ${data.value}`;
    },
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    top: "15%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    data: props.xAxisData,
    axisLabel: {
      interval: 0,
      rotate: 30, // 旋转角度
      formatter: function (value) {
        // 旋转时也限制最多4个字
        return value.length > 4 ? value.substring(0, 4) + "..." : value;
      },
      width: 60, // 固定宽度
    },
  },
  yAxis: {
    type: "value",
  },
  series: [
    {
      type: "bar",
      barWidth: "60%",
      barMaxWidth: 30,
      itemStyle: {
        color: (params) => generateGradientColors(6)[params.dataIndex % 6],
        borderRadius: [4, 4, 0, 0],
        borderWidth: 0,
        shadowColor: "rgba(0, 217, 255, 0.3)",
        shadowBlur: 8,
        shadowOffsetY: 2,
      },
      emphasis: {
        itemStyle: {
          shadowColor: "rgba(0, 217, 255, 0.5)",
          shadowBlur: 10,
        },
      },
      label: {
        show: true,
        position: "top",
        color: "#fff",
        fontWeight: "bold",
        formatter: "{c}",
      },
      data: props.seriesData,
    },
  ],
});

watch(
  () => props.xAxisData,
  (val) => {
    option.value.xAxis.data = val;
  },
  { deep: true }
);

watch(
  () => props.seriesData,
  (val) => {
    option.value.series[0].data = val;
  },
  { deep: true }
);
</script>

<style scoped>
.chart {
  height: 245px;
  width: 100%;
}
</style>
